<script setup lang="ts">
  import { nextTick, PropType, ref, watch } from 'vue'
  import { useGetGoodTypes } from '@/services/pages/good/useType'
  import { useGetGoods } from '@/services/pages/order/create'
  import { useGetBrandOptions } from '@/services/pages/good/useBrand'
  import _ from 'lodash'
  import Pagination from '@/components/Pagination/index.vue'
  import { TableInstance } from 'element-plus'
  import { SelectedGood } from '../../types'

  const { total, loading, goodTypes, getGoodTypesParam, getGoodTypes } = useGetGoodTypes()
  const { goods, goodsTotal, getGoodsParam, getGoodsLoading, getGoods } = useGetGoods()
  const {
    loading: getBrandOptionsLoading,
    options,
    getBrandOptionsParam,
    getBrandOptions,
  } = useGetBrandOptions()

  defineOptions({
    name: 'GoodSelectModalOrderGoodSettle',
  })

  const props = defineProps({
    defaultSelectedIds: {
      type: Array as PropType<
        Array<{
          goodId: string
          goodSpecId: string
        }>
      >,
      default: () => [],
    },
  })

  const emits = defineEmits<{
    (e: 'confirm', value: Array<SelectedGood>): void
    (e: 'del', value: Array<SelectedGood>): void
  }>()

  const visible = defineModel('visible', { type: Boolean, default: false })
  const currentSelectedType = ref(null)
  const tableInstance = ref<TableInstance | null>(null)
  const paginationInstance = ref<InstanceType<typeof Pagination> | null>(null)
  const selectedGoods = ref<Array<SelectedGood>>([])
  const delSelectGoods = ref<Array<SelectedGood>>([])

  const handleGoodTypeCurrentPageChange = (currentPage: number) => {
    getGoodTypesParam.value.limit = currentPage
  }

  const handleGoodTypeChange = (goodTypeId: string) => {
    currentSelectedType.value = goodTypeId
    onReset()
  }

  const setGoodPaginationPageSize = () => {
    if (document.body.clientHeight >= 945) {
      getGoodTypesParam.value.limit = 20
    }

    if (document.body.clientHeight < 945 && document.body.clientHeight >= 900) {
      getGoodTypesParam.value.limit = 18
    }

    if (document.body.clientHeight < 900 && document.body.clientHeight >= 768) {
      getGoodTypesParam.value.limit = 14
    }

    if (document.body.clientHeight < 768 && document.body.clientHeight >= 720) {
      getGoodTypesParam.value.limit = 13
    }
    getGoodTypes()
  }

  const onReset = () => {
    getGoodsParam.value = {
      brandId: '',
      keyword: '',
      limit: 50,
      page: 1,
      typeId: currentSelectedType.value,
      factoryId: '',
    }
    getGoodList()
  }

  const handleGetBrandOptions = _.debounce((keyword: string) => {
    if (getBrandOptionsParam.value.name !== keyword) {
      getBrandOptionsParam.value.name = keyword
      getBrandOptions()
    }
  }, 600)

  /**
   * 获取产品列表
   */
  const getGoodList = () => {
    nextTick(async () => {
      if (paginationInstance.value) {
        getGoodsParam.value.limit = paginationInstance.value.size
        getGoodsParam.value.page = paginationInstance.value.current
        await getGoods()
        if (tableInstance.value) {
          const selectedGoodIds: Array<{ goodId: string; goodSpecId: string }> = [
            ...props.defaultSelectedIds,
          ]
          selectedGoods.value.forEach((good) => {
            const isGoodIdExist = selectedGoodIds.some(
              (item) => item.goodId === good.goodId && item.goodSpecId === good.goodSpecId,
            )
            if (!isGoodIdExist) {
              selectedGoodIds.push({
                goodId: good.goodId,
                goodSpecId: good.goodSpecId,
              })
            }
          })

          goods.value.forEach((good) => {
            const selectGoodId = selectedGoodIds.some(
              (item) => item.goodId === good.id && item.goodSpecId === good.specId,
            )
            if (selectGoodId) {
              tableInstance.value.toggleRowSelection(good, true)
            }
          })
        }
      }
    })
  }

  /**
   * 移除产品
   * @param {Array<OrderGood>} selectionGoods - 选择的产品列表
   * @param {OrderGood} row - 当前操作的产品
   */
  const handleRemoveGood = (selectionGoods: Array<OrderGood>, row: OrderGood) => {
    const index = selectionGoods.findIndex(
      (selectionGood) => selectionGood.id === row.id && selectionGood.specId === row.specId,
    )
    if (index === -1) {
      delSelectGoods.value.push({
        id: '',
        payNetworkFee: '0',
        goodName: row.name,
        goodId: row.id,
        goodSpecId: row.specId,
        goodType: row.type,
        goodSecondType: row.typeTwo,
        goodThreeType: row.typeThree,
        code: row.code,
        goodSpecName: row.specName,
        model: row.model,
      })
    }
  }

  /**
   * 产品选择事件
   * @param {Array<OrderGood>} goods - 产品列表
   */
  const handleSelectGood = (goods: Array<OrderGood>) => {
    goods.forEach((good) => {
      const isGoodExist = selectedGoods.value.some(
        (selectGood) => selectGood.goodId === good.id && selectGood.goodSpecId === good.specId,
      )
      if (!isGoodExist) {
        selectedGoods.value.push({
          id: '',
          payNetworkFee: '0',
          goodName: good.name,
          goodId: good.id,
          goodSpecId: good.specId,
          goodType: good.type,
          goodSecondType: good.typeTwo,
          goodThreeType: good.typeThree,
          code: good.code,
          goodSpecName: good.specName,
          model: good.model,
        })
      }
    })
  }

  /**
   * 产品全选/全部反选事件
   * @param {Array<OrderGood>} goods - 产品列表
   */
  const handleSelectAllGood = (goods: Array<OrderGood>) => {
    delSelectGoods.value.length = 0

    goods.forEach((good) => {
      const isGoodExist = selectedGoods.value.some(
        (selectGood) => selectGood.goodId === good.id && selectGood.goodSpecId === good.specId,
      )
      if (!isGoodExist) {
        selectedGoods.value.push({
          id: '',
          payNetworkFee: '0',
          goodName: good.name,
          goodId: good.id,
          goodSpecId: good.specId,
          goodType: good.type,
          goodSecondType: good.typeTwo,
          goodThreeType: good.typeThree,
          code: good.code,
          goodSpecName: good.specName,
          model: good.model,
        })
      }
    })
  }

  /**
   * 弹窗确定事件
   */
  const onConfirm = () => {
    visible.value = false
    emits('confirm', [...selectedGoods.value])
    emits('del', [...delSelectGoods.value])
  }

  watch(
    visible,
    (value) => {
      selectedGoods.value.length = 0
      if (value) {
        setGoodPaginationPageSize()
        window.addEventListener('resize', setGoodPaginationPageSize)
        getGoodList()
      }

      if (!value) {
        window.removeEventListener('resize', setGoodPaginationPageSize)
      }
    },
    { immediate: true },
  )
</script>

<template>
  <h-drawer v-model="visible" title="选择产品" :width="1100" unit="px" :h-drawer-padding-top="18">
    <div class="select-good-modal-wrapper">
      <div v-loading="loading" class="sidebar">
        <div class="title">
          <div class="text">产品分类</div>
        </div>
        <div class="content">
          <ul class="good-types">
            <li
              :class="{
                'good-type-item': true,
                'active-good-type-item': currentSelectedType === null,
              }"
              @click="handleGoodTypeChange(null)"
              >全部</li
            >
            <li
              v-for="goodType in goodTypes"
              :key="goodType.id"
              :class="{
                'good-type-item': true,
                'active-good-type-item': currentSelectedType === goodType.id,
              }"
              @click="handleGoodTypeChange(goodType.id)"
            >
              {{ goodType.name }}
            </li>
          </ul>
          <div class="pagination">
            <el-pagination
              hide-on-single-page
              size="small"
              :pager-count="5"
              :current-page="getGoodTypesParam.page"
              :page-size="getGoodTypesParam.limit"
              :total="total"
              layout="prev, pager, next"
              @current-change="handleGoodTypeCurrentPageChange"
            />
          </div>
          <div class="total"> 共{{ total }}条</div>
        </div>
      </div>
      <div class="body">
        <div class="header">
          <div class="title">
            <div class="text">产品列表</div>
          </div>
          <div class="search">
            <el-select
              v-model="getGoodsParam.brandId"
              placeholder="请选择品牌"
              :loading="getBrandOptionsLoading"
              clearable
              filterable
              :filter-method="handleGetBrandOptions"
              @change="getGoodList"
              @clear="getGoodList"
            >
              <el-option
                v-for="(brand, brandIndex) in options"
                :key="brandIndex"
                :label="brand.name"
                :value="brand.id"
              />
            </el-select>
            <el-input
              v-model.trim="getGoodsParam.keyword"
              placeholder="产品名称/产品型号/产品规格"
              clearable
              @keyup.enter="getGoodList"
              @clear="getGoodList"
            />
            <h-button type="primary" @click="getGoodList">
              <el-icon>
                <Search></Search>
              </el-icon>
              搜索
            </h-button>
            <h-button @click="onReset">
              <el-icon>
                <RefreshRight></RefreshRight>
              </el-icon>
              重置
            </h-button>
          </div>
        </div>
        <div class="table">
          <el-table
            ref="tableInstance"
            v-loading="getGoodsLoading"
            height="100%"
            :data="goods"
            :border="true"
            :stripe="true"
            @select="handleRemoveGood"
            @select-all="handleSelectAllGood"
            @selection-change="handleSelectGood"
          >
            <el-table-column type="selection" fixed="left" :align="'center'" />
            <el-table-column type="index" fixed="left" :align="'center'" width="60" label="序号" />
            <el-table-column label="编号" width="160" show-overflow-tooltip prop="code" />
            <el-table-column label="品牌" show-overflow-tooltip prop="brand" />
            <el-table-column label="产品名称" width="300" show-overflow-tooltip prop="name" />
            <el-table-column label="型号" show-overflow-tooltip prop="model" />
            <el-table-column label="规格" width="340" show-overflow-tooltip prop="specName" />
            <el-table-column label="规格图片">
              <template #default="scope">
                <div v-if="scope.row.image" class="pic">
                  <h-image
                    :src="scope.row.image"
                    fit="contain"
                    :show-del-btn="false"
                    :padding="2"
                    :width="40"
                    :height="25"
                  />
                </div>
              </template>
            </el-table-column>
            <el-table-column
              label="质保时间(天)"
              width="100"
              show-overflow-tooltip
              prop="warrantyDay"
            />
          </el-table>
        </div>
        <div class="pagination">
          <Pagination
            ref="paginationInstance"
            :list_total="goodsTotal"
            @size-change="getGoodList"
            @current-change="getGoodList"
          ></Pagination>
        </div>
      </div>
    </div>
    <template #footer>
      <h-button is-modal type="primary" @click="onConfirm">确定</h-button>
      <h-button is-modal @click="visible = false">取消</h-button>
    </template>
  </h-drawer>
</template>

<style scoped lang="scss">
  .select-good-modal-wrapper {
    height: 99%;
    display: flex;
    column-gap: 12px;

    .sidebar {
      width: 250px;
      height: 100%;
      display: flex;
      flex-direction: column;
      row-gap: 5px;

      .title {
        height: 28px;
        display: flex;
        align-items: center;
        justify-content: flex-start;

        .text {
          border-left: 3px solid $primaryColor;
          padding-left: 6px;
          box-sizing: border-box;
          font-weight: bold;
          font-size: 14px;
        }
      }

      .content {
        box-sizing: border-box;
        border: 1px solid #e5e5e5;
        padding: 6px 12px;
        height: calc(100% - 28px - 5px - 5px - 28px);
        overflow: auto;

        .good-types {
          display: flex;
          flex-direction: column;
          row-gap: 3px;

          .good-type-item {
            list-style: none;
            height: 28px;
            line-height: 28px;
            padding: 0 14px;
            box-sizing: border-box;
            cursor: pointer;

            &:hover {
              background-color: rgba(0, 123, 255, 0.137254902) !important;
              color: $primaryColor;
            }
          }

          .active-good-type-item {
            background-color: rgba(0, 123, 255, 0.137254902) !important;
            color: $primaryColor;
          }
        }
      }

      .pagination {
        :deep(.el-pagination) {
          display: flex;
          justify-content: center;
        }
      }

      .total {
        display: flex;
        justify-content: center;
      }
    }

    .body {
      flex: 1;
      width: 0;
      height: 100%;
      display: flex;
      flex-direction: column;
      row-gap: 5px;

      .header {
        display: flex;
        justify-content: space-between;

        .title {
          display: flex;
          align-items: center;

          .text {
            padding-left: 6px;
            border-left: 3px solid $primaryColor;
            font-size: 14px;
            font-weight: bold;
          }
        }

        .search {
          display: flex;
          column-gap: 5px;

          :deep(.el-input) {
            width: 200px;
          }

          :deep(.el-select) {
            width: 140px;
          }
        }
      }

      .table {
        max-height: calc(100% - 66px);
      }

      .pagination {
        display: flex;
        justify-content: flex-end;
      }
    }

    .header {
      display: flex;
      column-gap: 12px;

      .commodity_type {
        width: 270px;
        display: flex;
        justify-content: flex-start;
        align-items: center;

        .title {
          font-size: 14px;
          padding-left: 6px;
          border-left: 3px solid $primaryColor;
          font-weight: bold;
        }
      }

      .commodity_table {
        width: calc(100% - 270px - 12px);
        display: flex;
        justify-content: space-between;
        align-items: center;

        .title {
          font-size: 14px;
          padding-left: 6px;
          border-left: 3px solid $primaryColor;
          font-weight: bold;
        }

        .search {
          display: flex;
          column-gap: 5px;

          :deep(.el-select) {
            width: 140px;
          }

          :deep(.el-input) {
            width: 200px;
          }
        }
      }
    }
  }
</style>
